<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Sort as sortModel;
use app\admin\model\Product as productModel;
use app\admin\model\News as newsModel;
use app\admin\model\About as aboutModel;
use app\admin\model\Project as projectModel;
use app\admin\model\Down as downModel;
use app\admin\validate\Sort as sortValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Sort extends Base{
    // 列表
    public function index(){
        $tabledir = input('tabledir'); $signid = input('signid'); $keyword = input('keyword');
        // 赋值状态
        if(!is_numeric($signid)) $signid = 1;
        View::assign('signid',$signid);

        // 所属模块不存在
	    if(empty($tabledir)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('tabledir'=>$tabledir)]);
        }

	    $order = ['sequence'=>'desc','id'=>'desc'];
		$list = sortModel::index($tabledir,12,$this->lang,$signid,$keyword,$order);
		View::assign('list',$list);
        View::assign('total',$list->total());
        View::assign('lastPage',$list->lastPage());

        return view();
    }

    // 添加编辑
    public function edit($id=0){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

		$rs = sortModel::find($id);
        View::assign('rs',$rs);
            
        if(!request()->isPost()){
            // 父级标题
            $parent_title = '';
            if(!empty($rs)){
            	$sortRs = Db::name('sort')->field('title')->where('id',$rs['parentid'])->find();
            	$parent_title = $sortRs['title'];
            }
            View::assign('parent_title',$parent_title);
			
			$where[] = ['lang','=',$this->lang]; $where[] = ['tabledir','=',$tabledir];
            View::assign('sort',getChildSort(Db::name('sort')->where($where)->select()));
			View::assign('tabledir',$tabledir);

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);
			
			// 前端列表页模板
            $suffix = config('view.view_suffix');
            $templatePath = app()->getRootPath().'template/'.$configArray['theme'].'/pc/'.$tabledir.'/';
            $templateList = array();
            if(is_dir($templatePath)){
                $dofile = new \common\Dofile();
                $templateArr = $dofile->getFiles($templatePath,false,$suffix);
                foreach ($templateArr as $preTempRs) {
                    if(strpos($preTempRs,'list_') !== false){
                        $templateList[] = $preTempRs;
                    }
                }
            }
            View::assign('listtemp',$templateList);
            View::assign('defaulttemp',"list_default");

			return view();
        }else{
            // 所属模块不存在
            if(empty($tabledir)){
                return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('tabledir'=>$tabledir)]);
            }

            // 表单验证
            try {
                validate(sortValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1002, 'msg' => $e->getMessage(), 'data' => '']);
            }
			
            $urlroute = input('urlroute');
            $urlWhere[] = ['lang','=',$this->lang]; $urlWhere[] = ['urlroute','=',$urlroute];
            // 语言目录下模型唯一性验证
            $moduleUrl = Db::name('module')->where($urlWhere)->field('urlroute')->find();
            // 语言目录下分类唯一性验证
            $sortUrl = Db::name('sort')->where($urlWhere)->count();
            
            if(($sortUrl >= 1 and input('urlroute') != $rs['urlroute']) or in_array($urlroute, array('tags'))){
                return json(['code' => 1003, 'msg' => lang('v_urlroute_tips'), 'data' => array('urlroute'=>$urlroute)]);
            }
            // if(!empty($moduleUrl)){
            //     return json(lang('v_sort_urlroute_tips'));
            // }

			try {
                sortModel::edit($id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
	}

    // 单个更新状态
    public function update_signid(){
        $id = input('id'); $signid = input('signid');
        // 参数不能为空
        if(empty($id) or empty($signid)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }
        // 软删除
        if($signid == 9) $signid = time();
        
        try {
            Db::name('sort')->where('id',$id)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 批量更新状态
    public function updateall_signid(){
        $selectid = input('selectid/a'); $signid = input('signid');
        // 参数错误
        if(empty($selectid) or empty($signid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
        // 软删除
        if($signid == 9) $signid = time();
        
        try {
            Db::name('sort')->where('id','in',$selectid)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('selectid'=>$selectid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
	
	// 单条删除
    public function delete_one(){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

		$id = input('id');
		// 参数不能为空
		if(empty($tabledir) or empty($id)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }

		// 含有模块禁止删除的分类
        $nodeletesortidArr = explode(',', $this->navModuleRs['no_delete_sortid']);
        if(in_array($id, $nodeletesortidArr)){
            return json(['code' => 1002, 'msg' => lang('c_nodelete_sortid_error'), 'data' => array('id'=>$id)]);
        }

		// 禁止删除含有子项的父项
        $hasChild = Db::name('sort')->where('parentid',$id)->find();
        if(!empty($hasChild)){
            return json(['code' => 1003, 'msg' => lang('c_delete_sort_child_first'), 'data' => array('id'=>$id)]);
        }

        // 禁止删除含有该分类的信息
        // $hasInfo = Db::name($tabledir)->where('sortid',$id)->find();
        // if(!empty($hasInfo)){
        //     return json(['code' => 1004, 'msg' => lang('c_delete_sort_info_first'), 'data' => array('id'=>$id)]);
        // }

        try {
            Db::name('sort')->delete($id);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 批量删除
    public function delete_all(){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

		$selectid = input('selectid/a');
		if(empty($selectid) or empty($tabledir)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }

		// 含有模块禁止删除的信息
        $nodeletesortidArr = explode(',', $this->navModuleRs['no_delete_sortid']);
        foreach ($selectid as $infoid) {
            if(in_array($infoid, $nodeletesortidArr)){
                return json(['code' => 1002, 'msg' => lang('c_nodelete_sortid_error'), 'data' => array('selectid'=>$selectid)]);
            }
            break;
        }

		foreach($selectid as $i => $rs){
		    $id = $selectid[$i];
		    // 禁止删除含有子项的父项
            $hasChild = Db::name('sort')->where('parentid',$id)->find();
            if(!empty($hasChild)){
                return json(['code' => 1003, 'msg' => lang('c_delete_sort_child_first'), 'data' => array('id'=>$id)]);
                break;
            }
            // 禁止删除含有该分类的信息
            // $hasInfo = Db::name($tabledir)->where('sortid',$id)->find();
            // if(!empty($hasInfo)){
            //     return json(['code' => 1004, 'msg' => lang('c_delete_sort_info_first'), 'data' => array('id'=>$id)]);
            // 	break;
            // }
		    $deleteid[] = $id;
	    }

        try {
            // 执行删除
            Db::name('sort')->delete($deleteid);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 批量更新
    public function update_all(){
		$id = input('id/a'); $sequence = input('sequence/a');
        // 参数不能为空
        if(empty($id) or empty($sequence)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }
        
		foreach($id as $i => $rs){
            $data[] = ['id'=>$id[$i],'sequence'=>$sequence[$i]];
        }

        try {
            $sort = new sortModel;
            $sort->saveAll($data,true);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
}